package com.example.handpose_front.HomePage;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.handpose_front.MainPage.MainActivity;
import com.example.handpose_front.R;
import com.example.handpose_front.callback.HomeCallBack.IExchangeLoginMode;
import com.example.handpose_front.dto.DataResponse;
import com.example.handpose_front.utils.LocalStorage;
import com.example.handpose_front.utils.OKHttpUtil.HttpUrl;
import com.example.handpose_front.utils.OKHttpUtil.OKHttpUtil;
import com.example.handpose_front.utils.OKHttpUtil.ResponseBody;
import com.example.handpose_front.utils.PhoneUtil;

import java.util.HashMap;
import java.util.Map;

public class LoginFragment extends Fragment {
    private View rootView;
    // login页面自定义组件
    private EditText phoneET;
    private EditText passwordET;
    private TextView exchangeTV;
    private Button loginBtn;

    // 用户输入
    private String phoneStr;
    private String passwordStr;

    // 响应体
    private DataResponse dataResponse;
    Map<String, String> map = new HashMap<>();
    private String userPhone;
    private String curDictionaryId = "";

    private IExchangeLoginMode exchangeLoginMode;

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 确保只赋值一次
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_login, container, false);
        }

        // 初始化控件
        initView();
        // 为控件添加事件(交换事件，登录事件)
        initEvent();

        return rootView;
    }

    // 用来接收父类实现的接口（callBack）
    public void setExchangeLoginMode(IExchangeLoginMode exchangeLoginMode) {
        this.exchangeLoginMode = exchangeLoginMode;
    }

    private void initEvent() {
        // 交换登录模式事件
        exchangeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 进行登录模式的切换
                exchangeLoginMode.exchangeLoginMode();
            }
        });
        // 点击登录按钮
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 验证用户输入是否合理
                if (v.getId() == loginBtn.getId() && isCorrect()) {
                    // 向后端发起登录请求
                    if (sendLoginRequest()) {
                        // 请求成功，进行页面跳转
                        // 提示用户登录成功
                        Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                        sendGetCurDictionaryRequest(userPhone);
                        Intent intent = new Intent(getActivity(), MainActivity.class);
                        startActivity(intent);
                    }
                    // 结束登录界面
                    getActivity().finish();
                } else {
                    // 提示用户输入不合理
                    Toast.makeText(getActivity(), "手机号或密码输入错误！", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private boolean sendLoginRequest() {
        // 向后端发起请求
        map.clear();

        map.put("userPhone", phoneStr);
        map.put("userPassword", passwordStr);

        String response = OKHttpUtil.postSyncRequest(HttpUrl.getBaseUrl(), map, "user", "login");
        dataResponse = ResponseBody.getResponseBody(response);

        if (dataResponse.getCode().equals("200")) {
            userPhone = dataResponse.getData().get("userPhone").toString();
            // 存储用户手机号到
            LocalStorage.setCurrentPhone(userPhone);

             // 用户登录成功
            return true;
        } else {
            // 提示错误信息
            Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private boolean isCorrect() {
        // 获取用户输入
        phoneStr = phoneET.getText().toString();
        passwordStr = passwordET.getText().toString();

        // 验证用户输入合理性
        if (phoneStr == null || passwordStr == null || phoneStr.equals("") || passwordStr.equals("")) {
            return false;
        }
        // 判断电话号格式是否正确
        if (!PhoneUtil.isMobileNO(phoneStr)) {
            return false;
        }

        return true;
    }

    public boolean sendGetCurDictionaryRequest(String userPhone) {
        map.clear();

        map.put("userPhone", userPhone);
        String response = OKHttpUtil.postSyncRequest(HttpUrl.getBaseUrl(), map, "curDictionary", "get_cur");
        dataResponse = ResponseBody.getResponseBody(response);
        if (dataResponse.getCode().equals("200")) {
            curDictionaryId = dataResponse.getData().get("curDictionaryId").toString();
            LocalStorage.setCurDictionaryId(curDictionaryId);
            // 获取词典成功
            return true;
        } else {
            // 提示错误信息
            Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private void initView() {
        // 初始化基本控件
        phoneET = rootView.findViewById(R.id.login_et_phone);
        passwordET = rootView.findViewById(R.id.login_et_password);
        loginBtn = rootView.findViewById(R.id.login_btn);
        exchangeTV = rootView.findViewById(R.id.login_tv_exchange);
    }

}
